package com.chuangsi.framework.security.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chuangsi.common.constant.CacheConstants;
import com.chuangsi.common.constant.Constants;
import com.chuangsi.common.constant.UserConstants;
import com.chuangsi.common.exception.ServiceException;
import com.chuangsi.common.exception.user.*;
import com.chuangsi.common.utils.DateUtils;
import com.chuangsi.common.utils.MessageUtils;
import com.chuangsi.common.utils.RegexUtils;
import com.chuangsi.common.utils.StringUtils;
import com.chuangsi.common.utils.ip.IpUtils;
import com.chuangsi.framework.manager.AsyncManager;
import com.chuangsi.framework.manager.factory.AsyncFactory;
import com.chuangsi.framework.redis.RedisCache;
import com.chuangsi.framework.security.LoginBody;
import com.chuangsi.framework.security.LoginUser;
import com.chuangsi.framework.security.context.AuthenticationContextHolder;
import com.chuangsi.project.system.domain.SysUser;
import com.chuangsi.project.system.service.ISysConfigService;
import com.chuangsi.project.system.service.ISysRoleService;
import com.chuangsi.project.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private UserDetailsServiceImpl userDetailsServiceImpl;

    /**
     * 登录验证
     *
     * @param loginType 登录类型  1:PC  2:APP
     * @param loginBody 登录实体
     * @return 结果
     */
    public String login(Integer loginType, LoginBody loginBody) {
        //如果是PC登录，那么就需要校验验证码
        if(loginType == 1){
            // 验证码校验
            validateCaptcha(loginBody.getUsername(), loginBody.getCode(), loginBody.getUuid());
        }
        // 登录前置校验
        loginPreCheck(loginBody.getUsername(), loginBody.getPassword());
        //是app登录，并且是客户登录，并且是有openid
        if(loginType == 2 && loginBody.getType() == 1 && StrUtil.isNotBlank(loginBody.getOpenId())){
            userService.insertCustomer(loginBody.getOpenId());
        }
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginBody.getUsername(), loginBody.getPassword());
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginBody.getUsername(), Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginBody.getUsername(), Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginBody.getUsername(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        loginUser.setRoles(roleService.getRolesByUserId(loginUser.getUserId()));
        //绑定openId
        bindOpenId(loginUser.getUserId(),loginBody.getOpenId());
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }



    /**
     * 登录验证
     *
     * @param openId 登录实体
     * @return 结果
     */
    public String wechatLogin( String openId) {
        userService.insertCustomer(openId);
        SysUser user = userService.selectUserByOpenId(openId);
        // 用户验证
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(user.getNickName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        UserDetails userDetail = userDetailsServiceImpl.createLoginUser(user);
        LoginUser loginUser = BeanUtil.copyProperties(userDetail, LoginUser.class);
        loginUser.setRoles(roleService.getRolesByUserId(loginUser.getUserId()));
        //绑定openId
        bindOpenId(loginUser.getUserId(),openId);
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }


    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 密码格式验证
        if (!RegexUtils.match(password,RegexUtils.PASSWORD)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new ServiceException("密码格式验证错误，请填入至少一个特殊字符，一个字母，一个数字的6-20位密码",500);
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    /**
     * 绑定OPNEID
     * @param userId 用户ID
     * @param openId OPENID
     */
    public void bindOpenId(Long userId,String openId) {
        //当openId和用户没有openId绑定时，才给他绑定
        if(StrUtil.isNotBlank(openId)){
            SysUser sysUser = userService.selectUserById(userId);
            if(sysUser!=null && StrUtil.isBlank(sysUser.getOpenId())){
                int count = userService.count(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getOpenId,openId).eq(SysUser::getDelFlag,"0"));
                if(count == 0){
                    sysUser.setOpenId(openId);
                    userService.updateUserProfile(sysUser);
                }
            }
        }
    }
}
